package chen.yi.component.log.filter;

import chen.yi.component.log.utils.ThreadMdcUtil;
import cn.hutool.core.util.StrUtil;
import jakarta.servlet.FilterChain;
import jakarta.servlet.ServletException;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import org.slf4j.MDC;
import org.springframework.core.annotation.Order;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.filter.OncePerRequestFilter;

import java.io.IOException;

import static chen.yi.component.log.constant.TraceIdConstant.TRACE_ID;
import static chen.yi.component.log.constant.TraceIdConstant.TRACE_ID_HEADER;

/**
 * 生成traceId过滤器
 * @author huat
 **/
@Component
@Order(Integer.MIN_VALUE)
public class MDCFilter extends OncePerRequestFilter {
    @Override
    protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain) throws ServletException, IOException {
        try {
            String traceId = request.getHeader(TRACE_ID_HEADER);
            if(StrUtil.isBlank(traceId)) {
                traceId=ThreadMdcUtil.generateTraceId(request);
            }
            MDC.put(TRACE_ID, traceId);
            ThreadMdcUtil.backupAndSet();
            response.addHeader(TRACE_ID_HEADER, traceId);
            filterChain.doFilter(request, response);
        }finally {
            ThreadMdcUtil.clear();
        }
    }
}
